import { EntityManager, Repository } from 'typeorm';
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { UserItem } from './entities/user-item.entity';
import { CreateUserItemDto } from './dto/create-user-item.dto';
import { PageQuery } from '../../../util/entity/page.entity';
import { buildQuery } from '../../../util/common-fn';
import { UpdateUserItemDto } from './dto/update-user-item.dto';
import { Shop } from '../shop/entities/shop.entity';
import { User } from '../../admin/user/entities/user.entity';

@Injectable()
export class UserItemService {
  constructor(
    @InjectRepository(UserItem)
    private userItemRepository: Repository<UserItem>,
  ) {}
  create(createUserItemDto: CreateUserItemDto) {
    return this.userItemRepository.save(createUserItemDto);
  }

  findAllWithPage(pageQuery: PageQuery<UserItem>) {
    return this.userItemRepository.findAndCount(buildQuery(pageQuery));
  }

  findOne(id: number) {
    return this.userItemRepository.findOneByOrFail({ id });
  }

  async findOrCreateOneByUserIdAndShop(
    userId: number,
    shop: Shop,
    tr: EntityManager,
  ) {
    const userItem = await tr.findOne(UserItem, {
      where: {
        user: {
          id: userId,
        },
        itemType: shop.itemType,
      },
    });
    if (userItem) {
      return userItem;
    } else {
      // 创建一个
      const newUserItem = new UserItem(shop.name, shop.itemType, shop.itemNum);
      const insertedItem = await tr.save(newUserItem);
      await tr
        .createQueryBuilder()
        .relation(User, 'userItems')
        .of(userId)
        .add(insertedItem.id);
      return await tr.findOneByOrFail(UserItem, { id: insertedItem.id });
    }
  }

  update(id: number, updateUserItemDto: UpdateUserItemDto) {
    return this.userItemRepository.update({ id }, updateUserItemDto);
  }

  remove(id: number) {
    return this.userItemRepository.softDelete({ id });
  }

  /**
   * 找到用户物品
   * @param userId
   */
  findAll(userId: number) {
    return this.userItemRepository.findBy({
      user: { id: userId },
    });
  }
}
